<script setup>
import request from '@/utils/request.js'


const { proxy } = getCurrentInstance();
const rfidList = ref([]);

const emit = defineEmits(['sub']);

let socket = null;
let host = window.location.hostname;
let urlPrev = '/rfid/';

function createWebsocket() {
  socket = new WebSocket(`ws://${host}:8085/rfid`);

  // Set up event listeners
  socket.onopen = () => {
    console.log('RFID WebSocket connection opened.');
  };

  socket.onmessage = (event) => {
    const data = event.data;
    const list = rfidList.value;
    if (list.indexOf(data) === -1) {
      list.push(data);
    }
  };

  socket.onerror = (error) => {
    console.error('WebSocket Error:', error);
  };

  socket.onclose = () => {
    console.log('WebSocket connection closed.');
  };

  return socket;
}

function closeWebsocket() {
  if (socket) {
    socket.close();
  }

}

// 启动RFID的读取
function startInventory() {
  return request({
    url: `${urlPrev}inventory`,
    method: 'put'
  }).then(response => {
    proxy.$modal.msgSuccess("开始RFID读取");
  })
}

// 停止RFID的读取
function stopInventory() {
  return request({
    url: `${urlPrev}/stopInventory`,
    method: 'put'
  }).then(response => {
    proxy.$modal.msgSuccess("停止RFID读取");
  })
}

function start() {
  // 启动websocket监听
  createWebsocket();
  // 发送盘点请求
  startInventory();
}

function stop() {
  closeWebsocket();
  stopInventory();
}

// 定义外部可以使用的属性或方法
defineExpose({
  start, stop
})
</script>

<template>
  <div style="padding: 10px">
    资产标签列表：
    <ul>
      <li v-for="rfid in rfidList">{{rfid}}</li>
    </ul>
  </div>
</template>

<style scoped lang="scss">

</style>